<template>
  <div class="article-container">
    <el-card class="filter-card">
      <div slot="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
          <el-breadcrumb-item>内容管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 数据筛选表单 -->
      <el-form ref="form" :inline="true" class="demo-form-inline" :model="form" label-width="100px" size="mini">
        <el-form-item label="文章状态">
          <el-select v-model="status" placeholder="请选择">
            <el-option label="全部" :value="''"></el-option>
            <el-option :label="item.text" :value="item.text" v-for="(item, index) in articleStatus" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章类型">
          <el-select v-model="channelId" placeholder="请选择">
            <el-option label="全部" :value="''"></el-option>
            <el-option :label="channel.category" :value="channel.category" v-for="(channel, index) in channels"
              :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker v-model="rangeDate" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="loading" @click="onSerarchArticles()">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- /数据筛选表单 -->
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        根据筛选条件共查询到 {{ articles.length }} 条结果：
      </div>
      <el-table :data="articles.slice(
        (currentPage - 1) * pagesize,
        currentPage * pagesize
      )" stripe style="width: 100%" class="list-table" size="mini" v-loading="loading">
        <el-table-column prop="cover" label="封面">
          <template slot-scope="scope">
            <el-image style="width: 50px; height: 50px" :src="cover" :fit="fit"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题">
        </el-table-column>
        <el-table-column prop="username" label="作者">
        </el-table-column>
        <el-table-column prop="category" label="类型">
        </el-table-column>
        <el-table-column prop="state" label="状态">
        </el-table-column>
        <el-table-column prop="pubulish_time" label="发布时间">
        </el-table-column>
        <el-table-column width="300px" label="操作">
          <!-- 如果需要自定义表格列模板，则把需要自定义的内容放到 template 里面 -->
          <template slot-scope="{row,$index}">
            <el-button size="mini" icon="el-icon-edit" type="primary" round
              @click="$router.push('/publish?id=' + row.id.toString())">修改
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" round @click="onDeleteArticle(row.id)">
              删除 </el-button>
            <el-button size="mini" type="success" icon="el-icon-message" round>文章详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination layout="  prev, pager, next, sizes, jumper" :page-sizes="[5, 10]" :page-size="pagesize"
        :total="articles.length" :pager-count="5" :current-page="currentPage" @current-change="handleCurrentChange"
        @size-change="handleSizeChange">
      </el-pagination>
      <!-- /列表分页 -->
    </el-card>
  </div>
</template>

<script>
import { getArticles, getCategorys, deleteArticles } from '@/api/essay'

export default {
  name: 'ArticleIndex',
  data() {
    return {
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      articles: [], // 文章数据列表
      dataSource: [],
      articleStatus: [
        { status: 1, text: '待审核', type: '' }, // 1
        { status: 2, text: '审核通过', type: 'success' }, // 2
        { status: 3, text: '审核失败', type: 'warning' }
      ],
      pageSize: 10, // 每页大小
      status: null, // 查询文章的状态，不传就是全部
      statuslist: [],//状态list
      channels: [], // 文章类型列表
      channelId: null, // 查询文章的频道
      rangeDate: null, // 筛选的范围日期
      loading: true, // 表单数据加载中 loading
      currentPage: 1, //展示第几页
      pagesize: 5, //每页的数据条数
    }
  },
  watch: {},
  async created() {
    this.loadChannels()
    this.loadArticles()
  },
  mounted() {
  },
  methods: {
    //获取文章列表
    async loadArticles() {
      // 展示加载中 loading
      this.loading = true;
      getArticles().then((res) => {
        console.log(res);
        this.articles = res || [];
        this.dataSource = res || [];
        console.log(this.articles);

      });
      // 关闭加载中 loading
      this.loading = false;
    },

    // 查询文章
    onSerarchArticles() {
      let searchList = [...this.dataSource];
      const { status, channelId, rangeDate, articles } = this;
      if (!status && !channelId && !rangeDate) {
        this.articles = searchList;
        return;
      }
      if (status) {
        searchList = searchList.filter((item) => {
          if (status && item.state == status) {
            return item;
          }
        });
      }
      if (channelId) {
        searchList = searchList.filter((item) => {
          if (channelId && item.category == channelId) {
            return item;
          }
        });
      }
      if (rangeDate) {
        // const time = rangeDate.toString();
        const beginTime = new Date(rangeDate[0]).getTime();
        const endTime = new Date(rangeDate[1]).getTime();
        searchList = searchList.filter((item) => {
          const nowTime = new Date(item.pubulish_time).getTime();
          if (rangeDate && (beginTime <= nowTime && nowTime <= endTime)) {
            return item;
          }
        });
      }
      this.articles = searchList;
      console.log(status, channelId, rangeDate, this.articles, searchList, "发发发");
    },

    //获取文章类型
    async loadChannels() {
      getCategorys().then((res) => {
        this.channels = res;
      });
    },

    // 删除文章
    onDeleteArticle(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteArticles(id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.loadArticles();
        }).catch(err => {
          console.log("获取数据失败" + err);
          this.$message({
            message: '删除失败'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 分页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.currentPage = 1
    },

    checkAuditTime(beginTime, endTime, nowTime) {
      var strb = beginTime.split(":");
      if (strb.length != 2) {
        return false;
      }

      var stre = endTime.split(":");
      if (stre.length != 2) {
        return false;
      }

      var strn = nowTime.split(":");
      if (stre.length != 2) {
        return false;
      }
      var b = new Date();
      var e = new Date();
      var n = new Date();

      b.setHours(strb[0]);
      b.setMinutes(strb[1]);
      e.setHours(stre[0]);
      e.setMinutes(stre[1]);
      n.setHours(strn[0]);
      n.setMinutes(strn[1]);

      if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
        return true;
      } else {
        alert("当前时间是：" + n.getHours() + ":" + n.getMinutes() + "，不在该时间范围内！");
        return false;
      }
    }

  }
}
</script>

<style scoped lang="less">
.filter-card {
  margin-bottom: 30px;
}

.list-table {
  margin-bottom: 20px;
}

.article-cover {
  width: 60px;
  background-size: cover;
}
</style>
